package cn.cxy.demo

import android.Manifest
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import com.qw.soul.permission.SoulPermission
import com.qw.soul.permission.bean.Permission
import com.qw.soul.permission.callbcak.CheckRequestPermissionListener
import kotlinx.android.synthetic.main.activity_main.*

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        button.setOnClickListener { applyPermissionAndCall() }
    }

    /**
     * 先申请权限，再打电话
     */
    private fun applyPermissionAndCall() {
        SoulPermission.getInstance()
            .checkAndRequestPermission(
                Manifest.permission.CALL_PHONE,
                object : CheckRequestPermissionListener {
                    override fun onPermissionOk(permission: Permission) {
                        call()
                    }

                    override fun onPermissionDenied(permission: Permission) {
                        toast("没权限，打不了😢")
                    }
                })
    }

    /**
     * 调用系统打电话功能，拨打10086
     */
    private fun call() {
        try {
            val intent = Intent(Intent.ACTION_CALL)
            intent.data = Uri.parse("tel:10086")
            startActivity(intent)
        } catch (e: SecurityException) {
            e.printStackTrace()
        }
    }

    private fun toast(text: String) = Toast.makeText(this, text, Toast.LENGTH_SHORT).show()
}